package com.cy.store.controller;

import com.cy.store.controller.ex.*;
import com.cy.store.entity.User;
import com.cy.store.service.IUserService;
import com.cy.store.service.ex.InsertException;
import com.cy.store.service.ex.UsernameDuplicatedException;
import com.cy.store.util.JsonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController{
    @Autowired
    private IUserService userService;

    /**
     * 注册
     * @param user
     * @return
     */
    @RequestMapping("/reg")
    public JsonResult<Void> reg(User user){
        userService.reg(user);
        return new JsonResult<>(Ok);

    }

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public JsonResult<User> login(String username, String password, HttpSession session){
        User data = userService.login(username, password);
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());
        //System.out.println(getUidFromSession(session));
        //System.out.println(getUsernameFromSession(session));
        return new JsonResult<User>(Ok,data);
    }

    /**
     * 修改密码
     * @param oldPassword
     * @param newPassword
     * @param session
     * @return
     */
    @RequestMapping("/change_password")
    public JsonResult<Void> changePassword(String oldPassword,String newPassword,HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.updatePasswordByUid(uid,username,oldPassword,newPassword);
        return new JsonResult<>(Ok);
    }

    @RequestMapping("/find_by_uid")
    public JsonResult<User> findByUid(HttpSession session){
        User data = userService.findByUid(getUidFromSession(session));
        return new JsonResult<>(Ok,data);
    }

    @RequestMapping("/change_info")
    public JsonResult<Void> changeInfo(User user,HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changeInfo(uid,username,user);
        return new JsonResult<>(Ok);
    }

    public static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;
    public static final List<String> AVATAR_TYPE = new ArrayList<>();
    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/gif");
        AVATAR_TYPE.add("image/bmp");
    }
    @RequestMapping("/change_avatar")
    public JsonResult<String> changeAvatar(HttpSession session, MultipartFile file){
        if (file.isEmpty()){
            throw new FileEmptyException("空文件");
        }
        if (file.getSize()>AVATAR_MAX_SIZE){
            throw new FileSizeException("文件大小超出限制");
        }

        String contentType = file.getContentType();
        System.out.println(contentType);
        if (!AVATAR_TYPE.contains(contentType)){
            throw new FileTypeException("不支持此类型文件");
        }
        String filename = file.getOriginalFilename();
        int index = filename.lastIndexOf(".");
        String suffix = filename.substring(index);
        System.out.println(suffix);
        String uuid = UUID.randomUUID().toString().toUpperCase();
        filename = uuid + suffix;
        String parent = session.getServletContext().getRealPath("upload");
        //String parent = "D:\\upload";
        System.out.println(parent);
        File dir = new File(parent);
        if (!dir.exists()){
            dir.mkdirs();
        }
        File iFile = new File(dir, filename);
        try {
            file.transferTo(iFile);
        } catch (FileStateException e){
            throw new FileStateException("文件状态异常");
        } catch (IOException e) {
            throw new FileUploadIOException("文件读写异常");
        }
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        String avatar = "/upload/" + filename;
        userService.changeAvatar(uid,username,avatar);
        return new JsonResult<>(Ok,avatar);
    }


    /*public JsonResult<Void> reg(User user){
        JsonResult<Void> jsonResult = new JsonResult<>();
        jsonResult.setState(200);
        jsonResult.setMessage("用户注册成功");
        try {
            userService.reg(user);
        } catch (UsernameDuplicatedException e) {
            jsonResult.setState(4000);
            jsonResult.setMessage(e.getMessage());
        }catch (InsertException e){
            jsonResult.setState(5000);
            jsonResult.setMessage(e.getMessage());
        }
        return jsonResult;

    }*/


}
